package com.xuanxing123.webapp.action.settings;

import com.opensymphony.xwork2.Preparable;
import com.xuanxing123.service.IndustryManager;
import com.xuanxing123.model.Industry;
import com.xuanxing123.webapp.action.BaseAction;

import java.util.List;

public class IndustryAction extends BaseAction implements Preparable {
    private IndustryManager industryManager;
    private List industries;
    private Industry industry;
    private Long id;
    private String query;

    public void setIndustryManager(IndustryManager industryManager) {
        this.industryManager = industryManager;
    }

    public List getIndustries() {
        return industries;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String industryId = getRequest().getParameter("industry.id");
            if (industryId != null && !industryId.equals("")) {
                industry = industryManager.get(new Long(industryId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        industries = industryManager.search(query, Industry.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Industry getIndustry() {
        return industry;
    }

    public void setIndustry(Industry industry) {
        this.industry = industry;
    }

    public String delete() {
        industryManager.remove(industry.getId());
        saveMessage(getText("industry.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            industry = industryManager.get(id);
        } else {
            industry = new Industry();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (industry.getId() == null);

        industryManager.save(industry);

        String key = (isNew) ? "industry.added" : "industry.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}